package pers.zc.activiti.thread.demo2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;

/**
 * @description 提交业务子类
 * @Author Lin FuYuan
 * @date 2020/5/28
 */
@Service
public class ChildTasks extends ParentStatus {
    @Autowired
    private TestThreadPool2 testThreadPool;
    public void runTasks() throws InterruptedException {
        //创建CompletionService对象
        CompletionService<Result> comp = new ExecutorCompletionService<Result>(testThreadPool.testDemoThreadPool());
        //创建多个作业
        for (int i = 0; i <10 ; i++) {
            //调用异步方法,记录状态为等待
            String str = String.valueOf(i);
            statusMap.put(String.valueOf(i),new Entity(WAIT));
            comp.submit(new TaskDemo(str));
        }
        //获取运行结果
        for (int i = 0; i <10 ; i++) {
            Future<Result> take = comp.take();
            try {
                //获取运行结果
                Result result = take.get();
                //修改最终状态
                statusMap.get(result.getKey()).setStatus(result.getResult()?DONE:FAILED);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        //到此处表示线程都执行完壁, 如果还有状态为running的  直接视为failed

        //根据业务情况定  删除所有状态数据
        statusMap.clear();
    }

    /**
     * 停止任务
     * @author Lin FuYuan
     * @param
     * @date 2020/5/28
     * @return void
     */
    public void stopTasks(){
        statusMap.forEach((k,v)->{
            v.getThread().interrupt();
        });
    }

}
